#include <cserver/context.h>
#include <cserver/server.h>
#include <boost/asio/signal_set.hpp>
#include <thread>
namespace csrv{
	Context::~Context() = default;
	ContextPtr Context::make(){
		return std::make_shared<Context>();
	}

	Context::Context()
	{
	}

	void Context::start(){
		timer = std::make_shared<WallTimer>(*this);
		timer->start();

		database = std::make_shared<Database>(*this);
		database->startWorker();

		console = std::make_shared<Console>(*this);
		console->start();

		loraUpstream = std::make_shared<LORAUpstream>(*this);
		loraUpstream->start();

		nodeUdp = std::make_shared<NodeUdp>(*this);
		nodeUdp->start();

		server = csrv::Server::make(*this);
		server->start();

		restapi = std::make_shared<RestApi>(*this);
		restapi->start();

		//boost::asio::io_service::work wk_aserver(ios_aserver), wk_client(ios_client);
		
		std::thread th_aserver([&]{
				boost::asio::signal_set signals(ios_aserver);
				signals.add(SIGPIPE);
				signals.async_wait([this](const boost::system::error_code& , int){ });
				ios_aserver.run();
				});
		std::thread th_client([&]{
				boost::asio::signal_set signals(ios_client);
				signals.add(SIGPIPE);
				signals.async_wait([this](const boost::system::error_code& , int){ });
				ios_client.run();
				});

		th_aserver.join();

		ios_client.stop();
		th_client.join();

		database->stopWorker();
		restapi->stop();
	}
	void Context::stop(){
		ios_aserver.stop();
		ios_client.stop();
	}
}

